package quick.start.core;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import quick.start.core.util.CoreLog;

import android.app.Activity;
import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.os.Bundle;

/**
 * 应用类
 * 增加Activity的注册和销毁
 */

public abstract class ApplicationBase extends Application implements ILifeCircle{
	
	private static ApplicationBase instance;
	private List<WeakReference<Activity>> activities = new ArrayList<WeakReference<Activity>>();
	private static boolean DEBUG_MODE = true;
	
	public static Application getApplication(){
		return instance;
	}
	
	public static boolean isDebugMode(){
		return DEBUG_MODE;
	}
	
	public static ApplicationBase getInstance(){
		return instance;
	}
	
	@Override
	public void onCreate(){
		super.onCreate();
		beforeCreate();
		instance = this;
		DEBUG_MODE = 0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE);
		CoreLog.init(DEBUG_MODE);
		afterCreate();
	}

	/**
	 * 退出应用
	 * finish所有注册的Activity并退出
	 */
	public void exit(){
		beforeFinish();
		instance.finishActivities();
		afterFinish();
		android.os.Process.killProcess(android.os.Process.myPid());
		System.exit(0);
	}
	
	public abstract void beforeCreate();

	public abstract void afterCreate();

	public abstract void beforeFinish();

	public abstract void afterFinish();
	
	public void registerActivity(Activity activity){
		activities.add(new WeakReference<Activity>(activity));
	}
	
	protected void finishActivities(){
		for(WeakReference<Activity> aRef : activities){
			Activity a = aRef.get();
			if(null != a && !a.isFinishing())
				a.finish();
		}
	}
}
